import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:gold/base/provider_scaffold.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/utils/xfg_utils.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:provider/provider.dart';

import 'web_view_model.dart';

/// Descriptions: 网页内置页面
/// User: tangzhentao
/// Date: 2:02 下午 2021/12/5
///

class WebViewPage extends StatefulWidget {
  final String? title;
  final String url;
  final bool extendBody;
  final bool isBackClose;

  const WebViewPage({super.key, this.title, required this.url, this.extendBody = false, this.isBackClose = false});

  @override
  State<StatefulWidget> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> with AutomaticKeepAliveClientMixin {
  late final WebViewModel _webViewModel;

  @override
  void initState() {
    _webViewModel = WebViewModel(widget.url, widget.title);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ProviderScaffold<WebViewModel>(
      model: _webViewModel,
      appBar: (ctx) => widget.extendBody ? null:(
          widget.isBackClose ?
          AppBar(
            systemOverlayStyle: SystemUiOverlayStyle.dark,
            leading: IconButton(
              onPressed: XfgNav.pop,
              icon: Icon(Icons.close_rounded, size: XfgSize().size24, color: XfgColor.text1),
            ),
            backgroundColor: XfgColor.white,
            surfaceTintColor: XfgColor.transparent,
            bottom: ctx.select<WebViewModel, bool>((value) => value.loading) ?PreferredSize(
                preferredSize: Size(XfgSize().screenWidth, XfgSize().size4),
                child: const LinearProgressIndicator(backgroundColor: Colors.white, color: XfgColor.theme)
            ):null,
            elevation: 0,
          )
              :
          xfgAppbar(
              title: widget.title,
              bottom: ctx.select<WebViewModel, bool>((value) => value.loading) ?PreferredSize(
                  preferredSize: Size(XfgSize().screenWidth, XfgSize().size4),
                  child: const LinearProgressIndicator(backgroundColor: Colors.white, color: XfgColor.theme)
              ) :null
          )
      ),
      builder: (ctx, web) => InAppWebView(
        initialUrlRequest: URLRequest(url: WebUri(widget.url)),
        initialSettings: web.settings,
        pullToRefreshController: web.pullToRefreshController,
        onWebViewCreated: web.setController,
        onLoadStart: (controller, url) {
          xfgPrint.call('开始加载：$url');
        },
        onPermissionRequest: (controller, request) async {
          return PermissionResponse(resources: request.resources, action: PermissionResponseAction.GRANT);
        },
        onLoadStop: (controller, url) async {
          final webTitle = await controller.getTitle();
          if ((web.title == null || web.title?.isEmpty == true) && webTitle?.isNotEmpty == true) {
            web.title = webTitle;
            web.notifyListeners();
          }
          xfgPrint.call('加载完成(${web.title}): $url');
        },
        onReceivedError: (controller, request, error) {
          xfgPrint.call('收到错误(${request.url})：${error.type}, ${error.description}');
          web.pullToRefreshController?.endRefreshing();
        },
        onProgressChanged: (controller, progress) {
          if (progress == 100) web.pullToRefreshController?.endRefreshing();
          web.loading = progress != 100;
        },
        onUpdateVisitedHistory: (controller, url, androidIsReload) {
          xfgPrint.call('onUpdateVisitedHistory($androidIsReload): $url');
        },
        onConsoleMessage: (controller, consoleMessage) {
          if (kDebugMode) {
            xfgPrint.call('onConsole: $consoleMessage');
          }
        },
      )
    );
  }

  @override
  bool get wantKeepAlive => true;
}